package cn.wit.sst.components;

import javafx.scene.Node;
import javafx.scene.effect.BlurType;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;

/**
 * 一个可以拖动的控件，并且可以指定拖动的范围
 *
 */
public class DraggableView extends Region {
    private double lastX, lastY;

    public DraggableView(Node contentView) {
    	this(contentView, null);
    }

    /**
     *
     * @param contentView - 可拖动的内容
     * @param anchorView  - 拖动范围在哪个组件的边界之内，为空的话，
     * 						拖动范围由DraggableView的父容器决定
     */
    public DraggableView(Node contentView, Node anchorView) {
        setEffect(new DropShadow(BlurType.GAUSSIAN,
                                 Color.rgb(0, 0, 0, 0.5), 8, 0, 0, 2));

        getChildren().add(contentView);

        setOnMousePressed((MouseEvent event) -> {
            lastX = event.getX();
            lastY = event.getY();
            toFront();
        });

        setOnMouseDragged((MouseEvent event) -> {
            double layoutX = getLayoutX() + (event.getX() - lastX);
            double layoutY = getLayoutY() + (event.getY() - lastY);

            Node boundsView = (anchorView == null) ? getParent() : anchorView;

            if ((layoutX >= 0) &&
                    (layoutX <= (boundsView.getLayoutBounds().getWidth() - getLayoutBounds().getWidth()))) {
                setLayoutX(layoutX);
            }

            if ((layoutY >= 0) &&
                    (layoutY <= (boundsView.getLayoutBounds().getHeight() - getLayoutBounds().getHeight()))) {
                setLayoutY(layoutY);
            }

            if ((getLayoutX() + (event.getX() - lastX) <= 0)) {
                setLayoutX(0);
            }
        });
    }
}
